package com.dwyinyuan.producer;

import com.dwyinyuan.enums.TangYunEnums;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Tangyun365Producer implements Runnable {

    private String name;
    private BlockingQueue<String> blockingQueue;

    public Tangyun365Producer(String name, BlockingQueue<String> blockingQueue) {
        this.name = name;
        this.blockingQueue = blockingQueue;
    }

    /**
     * 正则表达式 2019-05-03/smallac046d1afaca1115f61f6357c297b786.jpg
     */
    private static final String PATTENS = "((?:19|20)\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])/(small)*[a-f0-9]{32}.jpg";

    @Override
    public void run() {
        try {
            TangYunEnums[] values = TangYunEnums.values();
            List<TangYunEnums> enums = Arrays.asList(values);
            for (TangYunEnums anEnum : enums) {
                // Jsoup 获取 HTML 并解析
                Document document = Jsoup.connect(anEnum.getUrl()).get();
                List<String> jpgUrls = this.convertToStrArr(PATTENS, document.outerHtml());
                for (String jpgUrl : jpgUrls) {
                    String trustUrl = jpgUrl.replaceAll("small", "");
                    String url = anEnum.getFileUrl().concat(trustUrl);
                    System.out.println("图片下载地址" + url);
                    blockingQueue.put(url);
                }
            }
            //消费者根据""退出while循环
            blockingQueue.put("");
            System.out.println("-----------------------------------");
            System.out.println(name + " is over");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<String> convertToStrArr(String patternStr, String inputStr) {
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(inputStr);
        List<String> list = new ArrayList<>();
        while (matcher.find()) {
            list.add(matcher.group());
        }
        return list.stream().filter(c -> c.contains("small")).collect(Collectors.toList());

    }
}
